<?php
$_SESSION[TINYMCE_UPLOAD] = 'uploads/instls/tinymce/';

$RIGHT_BAR_WIDTH = 320;
$DEF_WIDTH = 950;
$DEF_HEIGHT = 550;

$parent_id = MiscUtils::getParam('parent_id', 0);
$page_id = MiscUtils::getParam('pid', 0);
$plugin_id = MiscUtils::getParam('pgid', 0);
$inst_id = MiscUtils::getParam('i', 0);


$cond_vals = new stdClass();
$cond_vals->c = 't.id = :v1';
$cond_vals->v = array(':v1' => $page_id);
$tmp = DbUtils::get($myPdo, 'pz2_page', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
if (count($tmp) > 0) {
  $data->page = $tmp[0];
}
$cond_vals = new stdClass();
$cond_vals->c = 't.id = :v1';
$cond_vals->v = array(':v1' => $plugin_id);
$opts = new stdClass();
$opts->select_expr = 't.*, t1.folder AS _folder';
$opts->join_expr = 'LEFT JOIN pz2_plugin AS t1 ON t1.id = t.plugin_id';
$tmp = DbUtils::get($myPdo, 'pz2_plugin_instance', $cond_vals, NULL, NULL, NULL, NULL, $opts)->d;
if (count($tmp) > 0) {
  $data->plugin = $tmp[0];
}
$cond_vals = new stdClass();
$cond_vals->c = 't.sys_id = :v1';
$cond_vals->v = array(':v1' => $system_id);
$opts = new stdClass();
$opts->select_expr = 't.id, t.parent_id, t.title, t.order';
$data->pages = DbUtils::get($myPdo, 'pz2_page', $cond_vals, 't.order', 'ASC', NULL, NULL, $opts)->d;

$data->uis = DbUtils::get($myPdo, 'pz2_ui', NULL, NULL, NULL, NULL, NULL, NULL)->d;
$data->plugins = DbUtils::get($myPdo, 'pz2_plugin', NULL, NULL, NULL, NULL, NULL, NULL)->d;
$cond_vals = new stdClass();
$cond_vals->c = 't.page_id = :v1';
$cond_vals->v = array(':v1' => $page_id);
$opts = new stdClass();
$opts->select_expr = 't.*, t1.folder AS _folder';
$opts->join_expr = 'LEFT JOIN pz2_plugin AS t1 ON t1.id = t.plugin_id';
$data->instances = DbUtils::get($myPdo, 'pz2_plugin_instance', $cond_vals, 't.name', 'ASC', NULL, NULL, $opts)->d;
if (isset($data->page)) {
  foreach ($data->instances as $instance) {
    $code = '{' . $instance->_folder . ':' . $instance->id . '}';
    $instance->_added = 0;
    if (strpos($data->page->html, $code) !== FALSE) {
      $instance->_added = 1;
    }
  }
}
?>
<style>
.form {
  background-color: #fff;
}
.form td {
  vertical-align: middle;
  padding: 2px 5px;
}
.form th.header {
  text-align: left;
  color: #fff;
  background-color: #e09696;
  padding-left: 5px;
  font-weight: bold;
  height: 25px;
}
.form td.title {
  background-color: #f1d0d0;
  border-top: 1px solid #fff;
  width: 150px;
}
.form td.content {
  width: 200px;
  padding: 0;
}
.form td.content input {
  width: 99%;
  border: solid 1px #ddd;
}
.form td.content select {
  width: 100%;
  border: solid 1px #ddd;
}
.form td.content textarea {
  resize: none;
  width: 99%;
  height: 70px;
  border: solid 1px #ddd;
  margin: 2px 0;
}
.list {
  border-left: 1px solid #ddd;
  border-top: 1px solid #ddd;
}
.list td {
  vertical-align: middle;
  text-align: left;
  padding: 2px; 
  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}
.list td.nosort {
  background-color: #dababa;
  font-weight: bold;
  
}
.list tr.none td {
  background-color: #fff;
}
.list tr.notadd td {
  background-color: #eee;
}
.list tr.curr td {
  background-color: #ff8000;
}
.imgbtn{
  background-color: #fff;
  border-bottom: 2px solid #666;
  border-top: 1px solid #666;
  border-right: 1px solid #666; 
  border-left: 1px solid #666;
  font-weight: bold;
  cursor: pointer;
  display: table-cell;
  width: 120px;
  height: 35px;
  text-align: center;
  vertical-align: middle;
  font-size: 14px;
}
.main {
  vertical-align: top;
  border-top: none;
}
.main div.content {
  background-color: #eee;
  border: 1px solid #aaa;
}
.main div.content2 {
  background-color: #fff;
  border: 1px solid #aaa;
  padding: 5px;
}
.panel {
  width: 950px;
}
.panel td.tab {
  width: 100px;
  font-size: 12px;
  font-family: Lucida Sans Unicode;
  padding: 5px 10px;
  border: 2px solid #bbb;
  background-color: #fff;
  cursor: pointer;
}
.panel td.tab:hover {
  background-color: #eee;
}
.panel td.selected {
  font-weight: bold;
  border-bottom: none;
  background-color: #eee;
}
.panel td.empty {
  border-bottom: 1px solid #aaa;
}
.image_button {
  background-color: #fff;
  border-bottom: 2px solid #666666;
  border-right: 2px solid #666666;
  border-top: 1px solid #bbbbbb;
  border-left: 1px solid #bbbbbb;
  font-weight: bold;
  cursor: pointer;
  display: inline-block;
  width: 60px;
  height: 25px;
  line-height: 25px;
  text-align: center;
  vertical-align: middle;
  color: #000;
}
.code_title {
  font-size: 14px;
  font-family: Lucida Sans Unicode;
  padding: 10px 2px 0 0;
}
.code_content {
  font-family: Helvetica, Geneva, Arial, Verdana, sans-serif;
  letter-spacing: 0.5px;
  border: none;
  width: 950px; 
  resize: vertical;
}
.mceEditor > table {
  width: 950px !important;
  height: 300px !important;
}
</style>
<table cellspacing="0" cellpadding="0" style="padding-bottom: 5px;">
  <tr>
    <td><div class="imgbtn" onclick="parent.location.href='http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=pages&tag=pages&sid=' . $system_id; ?>'">List of Pages</div></td>
    <td style="padding: 0 10px; vertical-align: middle;"><b>Selected</b><br><img src="assets/imgs/right.gif" alt=""></img></td>
    <td>
      <div class="imgbtn"
        <?php if (isset($data->page)) { ?>
        onclick="parent.location.href='http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id . '&pid=' . $data->page->id; ?>'"><?php echo ($data->page->title == '') ? 'Untitled' : $data->page->title; ?>
        <?php } else { ?>
        >New Page
        <?php } ?>
      </div>
    </td>
    <?php if (isset($data->plugin)) { ?>
    <td style="padding: 0 10px; vertical-align: middle;"><b>Selected</b><br><img src="assets/imgs/right.gif" alt=""></img></td>
    <td><div class="imgbtn"><?php echo $data->plugin->name; ?></div></td>
    <?php } ?>
  </tr>
</table>
<table cellPadding=0 cellSpacing=0>
  <tr>
    <td style="width: 950px; display: <?php echo (isset($data->plugin)) ? 'none' : 'table-cell'; ?>" class="main">
      <table class="panel" cellPadding=0 cellSpacing=0>
        <tr>
          <td id="visual_tab" class="tab selected" onclick="set_mode(0);">Visual</td>
          <td id="code_tab" class="tab" onclick="set_mode(1);" style="border-left: none;">Code</td>
          <td class="empty"></td>
        </tr>
      </table>
      <div class="content">
        <div id="visual_div"><textarea id="page_content" style="width: 950px; height:600px;"><?php if (isset($data->page)) echo $data->page->html; ?></textarea></div>
        <div id="code_div" style="display: none;">
          <textarea id="code_content" class="code_content" style="height:600px;" onchange="_html = this.value;"><?php if (isset($data->page)) echo $data->page->html; ?></textarea>
        </div>
        <div>
          <div class="code_title">&ltscript type="text/javascript"&gt</div>
          <textarea id="js" class="code_content" style="width: 950px; height:120px;" onchange="_js = this.value;"><?php if (isset($data->page)) echo $data->page->js; ?></textarea>
          <div class="code_title">&lt/script&gt</div>
          <div class="code_title">&ltstyle&gt</div>
          <textarea id="css" class="code_content" style="width: 950px; height:120px;" onchange="_css = this.value;"><?php if (isset($data->page)) echo $data->page->css; ?></textarea>
          <div class="code_title">&lt/style&gt</div>
        </div>
      </div>
    </td>
    <td style="width: 950px; display: <?php echo (isset($data->plugin)) ? 'table-cell' : 'none'; ?>;" class="main">
      <div class="content2">
        <table class="form" width="320px;" cellPadding=0 cellSpacing=0>
          <tr>
          <td class="title">Code to Insert</td>
          <td class="content" id="updt_code" ><?php if (isset($data->plugin)) echo '{' . $data->plugin->_folder . ':' . $data->plugin->id . '}'; ?></td>
        </tr>
          <tr>
            <td class="title">Title</td>
            <td class="content"><input id="updt_title" value="<?php if (isset($data->plugin)) echo $data->plugin->name; ?>" type="text" onchange="CheckUtils.addToArray(_checks_updt, this, check_empty, _errors_updt);"></input></td>
          </tr>
          <tr>
            <td class="title">Width</td>
            <td class="content"><input id="updt_width" value="<?php if (isset($data->plugin)) echo $data->plugin->width; ?>" type="text" onchange="CheckUtils.addToArray(_checks_updt, this, check_number, _errors_updt);"></input></td>
          </tr>
          <tr>
            <td class="title">Height</td>
            <td class="content"><input id="updt_height" value="<?php if (isset($data->plugin)) echo $data->plugin->height; ?>" type="text" onchange="CheckUtils.addToArray(_checks_updt, this, check_number, _errors_updt);"></input></td>
          </tr>
        </table>
        <div style="text-align: right; width: 320px;">
          <input type="submit" value="Update" onclick="check_update_plugin();"></input>
        </div>
      </div>
      <div>&nbsp;</div>
      <div>
        <script type="text/javascript">
          function update_height() {
            var ifm = document.getElementById("pg_admin");
            if (ifm && !window.opera){
              if (ifm.contentDocument && ifm.contentDocument.body){
                var body = ifm.contentDocument.body;
                var html = ifm.contentDocument.documentElement;
                ifm.height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
              }
            }
          }
        </script>
        <iframe id="updt_admin" onload="update_height();" width="100%" height="550" frameborder="0"  marginwidth="0" marginheight="0" allowtransparency="true" <?php if (isset($data->plugin)) echo 'src="../../../exts/plugins/' . $data->plugin->_folder . '/admin.php?pgid=' . $plugin_id . '"'; ?>></iframe>
      </div>
    </td>
    <td style="width: 320px; vertical-align: top; padding-left: 10px;">
      <table class="form" width="100%" cellPadding=0 cellSpacing=0>
        <tr><th class="header" colspan=2>Basic</th></tr>
        <tr>
          <td class="title">Title</td>
          <td class="content"><input id="title" type="text" value="<?php if (isset($data->page)) echo $data->page->title; ?>"></input></td>
        </tr>
        <tr>
          <td class="title">Parent</td>
          <td class="content"><select id="parent"></select></td>
        </tr>
        <tr>
          <td class="title">Home Page</td>
          <td style="text-align: left;"><input id="home" type="checkbox" <?php if ((isset($data->page) && $data->page->is_default == 1) || count($data->pages) == 0) echo 'checked="true" disabled="true"'; ?>></input></td>
        </tr>
        <tr>
          <td class="title">Visible</td>
          <td style="text-align: left;"><input id="visible" type="checkbox" <?php if (isset($data->page) && $data->page->is_visible == 1) echo 'checked="true"'; if (!isset($data->page)) echo 'checked="true"'; ?>></input></td>
        </tr>
        <tr><th class="header" colspan=2>SEO</th></tr>
        <tr>
          <td class="title">Description</td>
          <td class="content"><textarea id="description"><?php if (isset($data->page)) echo $data->page->description; ?></textarea></td>
        </tr>
        <tr>
          <td class="title">Key Words</td>
          <td class="content"><textarea id="keywords"><?php if (isset($data->page)) echo $data->page->keywords; ?></textarea></td>
        </tr>
      </table>
      <span class="image_button" onclick="save();">Save</span>
      <?php if (isset($data->page)) { ?>
      <span class="image_button" onclick="remove();">Delete</span>
      <span style="width: 120px;" class="image_button" onclick="parent.location.href='http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id; ?>';">Create New Page</span>
      <?php } ?>
      <?php if (isset($data->page)) { ?>
      <div>&nbsp;</div>
      <table class="form" width="100%" cellPadding=0 cellSpacing=0>
        <tr><th class="header" colspan=2>New Plugin</th></tr>
        <tr>
          <td class="title">Plugins</td>
          <td class="content">
            <select id="pg_select">
              <option value="0">-</option>
              <?php foreach ($data->plugins as &$plugin) { ?>
                <option value="<?php echo $plugin->id; ?>"><?php echo $plugin->folder; ?></option>
              <?php } ?>
            </select>
          </td>
        </tr>
        <tr>
          <td class="title">Title</td>
          <td class="content"><input id="pg_title" type="text" onchange="CheckUtils.addToArray(_checks_add, this, check_empty, _errors_add);"></input></td>
        </tr>
        <tr>
          <td class="title">Width</td>
          <td class="content"><input id="pg_width" type="text" value="<?php echo $DEF_WIDTH; ?>" onchange="CheckUtils.addToArray(_checks_add, this, check_number, _errors_add);"></input></td>
        </tr>
        <tr>
          <td class="title">Height</td>
          <td class="content"><input id="pg_height" type="text" value="<?php echo $DEF_HEIGHT; ?>" onchange="CheckUtils.addToArray(_checks_add, this, check_number, _errors_add);"></input></td>
        </tr>
      </table>
      <div style="text-align: right;"><input type="submit" value="Add Plugin" onclick="check_add_plugin();"></input></div>
      <div>&nbsp;</div>
      <table id="instld_plugins" class="list" width="100%" cellPadding=0 cellSpacing=0>
        <tr>
          <td class="nosort">Title</td>
          <td width="50px" class="nosort">Plugin</td>
          <td width="25px" class="nosort">W</td>
          <td width="25px" class="nosort">H</td>
          <td width="20px" class="nosort"></td>
        </tr>
      </table>
      <?php } ?>
    </td>
  <tr>
</table>
<script type="text/javascript" src="../../../incls/js/pageutils.js"></script>
<script type="text/javascript" src="../../../libs/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../../../libs/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script type="text/javascript" src="../../../incls/js/checkutils.js"></script>
<script type="text/javascript">
  var _checks_add = [];
  var _errors_add = [];
  var _checks_updt = [];
  var _errors_updt = [];
  var _html = '';
  var _js = '';
  var _css = '';
  //Because tinymce's onchange is not working properly
  var _mode = 0;
  var _instances = JSON.parse('<?php echo addslashes(json_encode($data->instances)); ?>');
  
  $(function(){
    set_parent(PageUtils.getRoot(JSON.parse('<?php echo addslashes(json_encode($data->pages)); ?>')), $('#parent')[0], '', true);
    _html = $('#code_content')[0].value;
    _js = $('#js')[0].value;
    _css = $('#css')[0].value;
    tinyMCE.init( {
      // General options
      mode: 'exact',
      elements: 'page_content',
      theme: 'advanced',

      plugins: 'pdw,filebrowser,autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist',
      // Theme options
      theme_advanced_buttons1: 'pdw_toggle,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,forecolor,backcolor,|,image,media,|,preview',
      theme_advanced_buttons2: 'search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime',
      theme_advanced_buttons3: 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,advhr,|,print,|,ltr,rtl,|,fullscreen',
      theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
      theme_advanced_toolbar_location: 'top',
      theme_advanced_toolbar_align: 'left',
      theme_advanced_statusbar_location: 'bottom',
      theme_advanced_resizing: true,

      file_browser_callback: 'filebrowser',
      pdw_toggle_on: '1',
      pdw_toggle_toolbars: '2,3,4',
      onchange_callback: function(inst) {
        _html = inst.getBody().innerHTML;
      },

      // Example content CSS (should be your site CSS)
      theme_advanced_font_sizes: '10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px',
    });
    update_instls();
  });

  function update_instls() {
    var table, tr, td, elm;
    table = $('#instld_plugins')[0];
    if (!table) {
      return;
    }
    MyUtils.removeTableRows(table, 1);
    for (var idx in _instances) {
      var obj = _instances[idx];
      tr = table.insertRow(-1);
      tr.className = 'none';
      if (obj._added == 0) {
        tr.className = 'notadd';
      } else if (obj.id == '<?php echo $plugin_id; ?>') {
        tr.className = 'curr';
      }
      td = tr.insertCell(-1);
      td.style.cursor = 'pointer';
      td._obj = obj;
      td.onclick = function() {
        if (this._obj.id == '<?php echo $plugin_id; ?>') {
          parent.location.href = 'http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id . '&pid=' . $page_id; ?>';
        } else {
          parent.location.href = 'http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id . '&pid=' . $page_id . '&pgid='; ?>' + this._obj.id;
        }
      }
      if (obj._added == 0) {
        elm = document.createElement('img');
        elm.src = 'assets/imgs/warning.png';
        td.appendChild(elm);
        td.onclick = function() {
          var r = window.confirm('Insert to page?');
          if (r) {
            //Not good, change mode for working
            _mode = 1;
            _html = '<p>{' + this._obj._folder + ':' + this._obj.id + '}</p>' + _html;
            save();
          }
        }
      }
      MyUtils.setMatchedText(td, obj.name, '', 25);
      td = tr.insertCell(-1);
      MyUtils.setMatchedText(td, obj._folder, '', 6);
      td = tr.insertCell(-1);
      td.appendChild(document.createTextNode(obj.width));
      td = tr.insertCell(-1);
      td.appendChild(document.createTextNode(obj.height));
      td = tr.insertCell(-1);
      elm = document.createElement('img');
      elm.src = 'assets/imgs/delete24.png';
      elm.style.cursor = 'pointer';
      elm._obj = obj;
      elm.onclick = function() {
        var r = window.confirm('Click OK to Proceed?');
        if (r) {
          var plugin_id = this._obj.id;
          $.ajax({
            type: 'POST',
            url: '<?php echo basename(__FILE__, '.php'); ?>.server.php',
            data: 'action=remove_plugin&q=' + encodeURIComponent(this._obj.id),
            success: function(msg){
              try {
                JSON.parse(msg);
                if (plugin_id == '<?php echo $plugin_id; ?>') {
                  parent.location.href = 'http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id . '&pid=' . $page_id; ?>';
                } else {
                  location.reload();
                }
              } catch (ex) {
                alert( 'Error: ' + ex.message );
              }
            }
          });
        }
      }
      td.appendChild(elm);
    }
    if (_instances.length == 0) {
      tr = table.insertRow(-1);
      tr.className = 'none';
      td = tr.insertCell(-1);
      td.colSpan = 5;
      td.appendChild(document.createTextNode('None'));
    }
  }

  function set_parent(node, elm, prefix, selectable) {
    var opt = new Option(((prefix == '') ? '' : prefix + ') ' ) + ((node.id != 0 && node.title == '') ? 'Untitled' : node.title), node.id);
    if (node.id == '<?php echo isset($data->page) ? $data->page->id : -1; ?>' || !selectable) {
      opt.disabled = true;
    }
    elm.options[elm.options.length] = opt;
    if ('<?php echo $parent_id; ?>' == node.id) {
      elm.selectedIndex = elm.options.length - 1;
    }
    if (node.id == '<?php echo isset($data->page) ? $data->page->parent_id : -1; ?>') {
      elm.selectedIndex = elm.options.length - 1;
    }
    for (var idx in node._children) {
      var obj = node._children[idx];
      set_parent(obj, elm, ((prefix == '') ? '(' : '\u2002' + prefix + '-' ) + (parseInt(idx, 10) + 1), !opt.disabled);
    }
  }

  function set_mode(mode) {
    //Because tinymce's onchange is not working properly
    _mode = mode;
    $('#visual_tab')[0].className = 'tab';
    $('#code_tab')[0].className = 'tab';
    $('#visual_div')[0].style.display = 'none';
    $('#code_div')[0].style.display = 'none';
    if (mode == 0) {
      $('#visual_div')[0].style.display = 'block';
      $('#visual_tab')[0].className += ' selected';
      tinyMCE.activeEditor.setContent(_html);
    } else if (mode == 1) {
      $('#code_div')[0].style.display = 'block';
      $('#code_tab')[0].className += ' selected';
      //Because tinymce's onchange is not working properly
      _html = tinyMCE.activeEditor.getContent();
      $('#code_content')[0].value = _html;
    }
  }

  function save() {
    if (_mode == 0) {
      //Because tinymce's onchange is not working properly
      _html = tinyMCE.activeEditor.getContent();
    }
    var obj = {
      <?php if (isset($data->page)) { ?>
      id: <?php echo $data->page->id; ?>,
      _parent_id: <?php echo $data->page->parent_id; ?>,
      order: <?php echo $data->page->order; ?>,
      <?php } else { ?>
      order: 0,
      <?php } ?>
      sys_id: <?php echo $system_id; ?>,
      parent_id: $('#parent')[0].options[$('#parent')[0].selectedIndex].value,
      
      title: $('#title')[0].value,
      description: $('#description')[0].value,
      keywords: $('#keywords')[0].value,
      is_default: $('#home')[0].checked ? 1 : 0,
      is_visible: $('#visible')[0].checked ? 1 : 0,
      html: _html,
      css: _css,
      js: _js
    };
    $.ajax({
      type: 'POST',
      url: '<?php echo basename(__FILE__, '.php'); ?>.server.php',
      data: 'action=save&q=' + encodeURIComponent(JSON.stringify(obj)),
      success: function(msg){
        try {
          var result = JSON.parse(msg);
          parent.location.href = 'http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id . '&pgid=' . $plugin_id . '&pid='; ?>' + result.id;
        } catch (ex) {
          alert( 'Error: ' + ex );
        }
      }
    });
  }
  
  function remove() {
    var r = window.confirm('Click OK to Proceed?');
    if (r) {
      $.ajax({
        type: 'POST',
        url: '<?php echo basename(__FILE__, '.php'); ?>.server.php',
        data: 'action=remove&q=' + encodeURIComponent('<?php echo isset($data->page) ? (json_encode($data->page)) : '[]'; ?>'),
        success: function(msg){
          try {
            JSON.parse(msg);
            parent.location.href = 'http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=pages&tag=pages&sid=' . $system_id; ?>';
          } catch (ex) {
            alert( 'Error: ' + ex );
          }
        }
      });
    }
  }

  function check_add_plugin() {
    CheckUtils.addToArray(_checks_add, $('#pg_title')[0], check_empty, _errors_add);
    CheckUtils.addToArray(_checks_add, $('#pg_width')[0], check_number, _errors_add);
    CheckUtils.addToArray(_checks_add, $('#pg_height')[0], check_number, _errors_add);
    add_plugin();
  }
  
  function add_plugin() {
    if (_checks_add.length > 0) {
      setTimeout('add_plugin();', 500);
      return;
    }
    if (_errors_add.length > 0) {
      return;
    }
    //Select Checker does not work properly
    if ($('#pg_select')[0].selectedIndex == 0) {
      window.alert('Select a Plugin');
      return;
    }
    var obj = {
      page_id: '<?php echo $page_id; ?>',
      plugin_id: $('#pg_select')[0].options[$('#pg_select')[0].selectedIndex].value,
      name: $('#pg_title')[0].value,
      width: $('#pg_width')[0].value,
      height: $('#pg_height')[0].value
    };
    $.ajax({
      type: 'POST',
      url: '<?php echo basename(__FILE__, '.php'); ?>.server.php',
      data: 'action=add_plugin&q=' + encodeURIComponent(JSON.stringify(obj)),
      success: function(msg){
        try {
          JSON.parse(msg);
          location.reload();
        } catch (ex) {
          alert( 'Error: ' + ex );
        }
      }
    });
  }

  function check_update_plugin() {
    CheckUtils.addToArray(_checks_updt, $('#updt_title')[0], check_empty, _errors_updt);
    CheckUtils.addToArray(_checks_updt, $('#updt_width')[0], check_number, _errors_updt);
    CheckUtils.addToArray(_checks_updt, $('#updt_height')[0], check_number, _errors_updt);
    update_plugin();
  }
  
  function update_plugin() {
    if (_checks_updt.length > 0) {
      setTimeout('update_plugin();', 500);
      return;
    }
    if (_errors_updt.length > 0) {
      return;
    }
    var obj = {
      id: '<?php echo $plugin_id; ?>',
      page_id: '<?php echo $page_id; ?>',
      plugin_id: '<?php echo (isset($data->plugin)) ? $data->plugin->plugin_id : 0; ?>',
      name: $('#updt_title')[0].value,
      width: $('#updt_width')[0].value,
      height: $('#updt_height')[0].value
    };
    $.ajax({
      type: 'POST',
      url: '<?php echo basename(__FILE__, '.php'); ?>.server.php',
      data: 'action=update_plugin&q=' + encodeURIComponent(JSON.stringify(obj)),
      success: function(msg){
        try {
          JSON.parse(msg);
          location.reload();
        } catch (ex) {
          alert( 'Error: ' + ex );
        }
      }
    });
  }
  
  function check_empty(inputElm, callbackFunc, errorArr) {
    if (jQuery.trim(inputElm.value) == '') {
      CheckUtils.addError(inputElm, errorArr, 'Required');
    }
    callbackFunc();
  }

  function check_number(inputElm, callbackFunc, errorArr) {
    if (jQuery.trim(inputElm.value) == '' ||isNaN(inputElm.value)) {
      CheckUtils.addError(inputElm, errorArr, 'Number Only');
    }
    callbackFunc();
  }
</script>